package com.vhall.component.service.account.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.vhall.component.service.account.MwGateMsgService;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dalong
 * @date 2021-04-28 19:23
 */
@Service
@Slf4j
public class MwGateMsgServiceImpl implements MwGateMsgService {

    private static final String HOST = "http://101.251.214.153:8901";

    @Value("${vhall.sms.user-id}")
    private String userId;

    @Value("${vhall.sms.password}")
    private String password;

    /**
     * 短信接口地址
     */
    private static final String DIFF_CONTENT_URI = "/MWGate/wmgw.asmx/MongateMULTIXSend";
    /**
     * 短信接口地址：发送相同内容
     */
    private static final String SAME_CONTENT_URI = "/MWGate/wmgw.asmx/MongateSendSubmit";

    @Override
    public boolean send(String mobile, String msgContent, boolean contentSame) {
        log.info("send msg, mobile {}, content {}", mobile, msgContent);
        Map<String, Object> contentMap = new HashMap<>(8);
        String url;
        if (contentSame) {
            contentMap.put("pszSubPort", "*&");
            contentMap.put("userId", userId);
            contentMap.put("password", password);
            contentMap.put("pszMobis", mobile);
            contentMap.put("pszMsg", msgContent);
            contentMap.put("iMobiCount", 1);
            url = HOST + SAME_CONTENT_URI;
        } else {
            contentMap.put("userId", userId);
            contentMap.put("password", password);
            contentMap.put("pszMobis", mobile);
            contentMap.put("multixmt", msgContent);
            url = HOST + DIFF_CONTENT_URI;
        }
        log.info("mobile {}, content {}", mobile, contentMap);
        HttpRequest httpRequest = HttpUtil.createPost(url);
        HttpResponse httpResponse = httpRequest.form(contentMap).execute();
        log.info("mobile {}, response {}", mobile, httpResponse.toString());
        String bodyStr = httpResponse.body();
        log.info("mobile {}, {}", mobile, bodyStr);
        // 解析XML
        String resultCode = "";
        try {
            Document document = DocumentHelper.parseText(bodyStr);
            Element rootElement = document.getRootElement();
            resultCode = rootElement.getText();
            log.info("resultCode {}", resultCode);
        } catch (DocumentException e) {
            log.error("msg send error, response {}", bodyStr);
        }
        return Long.parseLong(resultCode) >= 0;
    }
}
